package com.fitness.servlet;

import com.fitness.dao.ProjectDAO;
import com.fitness.dao.ReservationDAO;
import com.fitness.entity.Project;
import com.fitness.entity.Reservation;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.List;

@WebServlet("/ReservationServlet")
public class ReservationServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理 GET 请求：显示预约页面（加载项目列表）
        ProjectDAO projectDAO = new ProjectDAO();
        List<Project> projectList = projectDAO.getProjectList();
        request.setAttribute("projectList", projectList);

        // 转发到预约页面
        request.getRequestDispatcher("/WEB-INF/views/member/reservationForm.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();

        // 验证会员是否已登录
        if (session.getAttribute("member") == null) {
            request.setAttribute("error", "请先登录");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

        try {
            // 1. 获取表单数据
            int memberId = Integer.parseInt(request.getParameter("memberId"));
            int projectId = Integer.parseInt(request.getParameter("projectId"));
            String reservationTimeStr = request.getParameter("reservationTime");

            // 2. 验证项目ID是否存在
            ProjectDAO projectDAO = new ProjectDAO();
            Project project = projectDAO.getProjectById(projectId);
            if (project == null) {
                request.setAttribute("error", "无效的项目ID，请参考项目列表");
                // 重新加载项目列表并显示错误
                request.setAttribute("projectList", projectDAO.getProjectList());
                request.getRequestDispatcher("/WEB-INF/views/member/reservationForm.jsp").forward(request, response);
                return;
            }

            // 3. 验证时间有效性（修复格式问题）
            Timestamp reservationTime = parseReservationTime(reservationTimeStr);

            if (reservationTime == null) {
                request.setAttribute("error", "预约时间格式不正确，请使用页面提供的日期选择器");
                request.setAttribute("projectList", projectDAO.getProjectList());
                request.getRequestDispatcher("/WEB-INF/views/member/reservationForm.jsp").forward(request, response);
                return;
            }

            if (reservationTime.before(new Timestamp(System.currentTimeMillis()))) {
                request.setAttribute("error", "预约时间必须在当前时间之后");
                request.setAttribute("projectList", projectDAO.getProjectList());
                request.getRequestDispatcher("/WEB-INF/views/member/reservationForm.jsp").forward(request, response);
                return;
            }

            // 4. 创建预约对象
            Reservation reservation = new Reservation();
            reservation.setMemberId(memberId);
            reservation.setProjectId(projectId);
            reservation.setReservationTime(reservationTime);
            reservation.setStatus("待确认");

            // 5. 保存到数据库
            ReservationDAO reservationDAO = new ReservationDAO();
            boolean success = reservationDAO.insertReservation(reservation);

            // 6. 处理结果
            if (success) {
                request.setAttribute("message", "预约成功！项目：" + project.getProjectName() + "，时间：" + reservationTime);
            } else {
                request.setAttribute("error", "预约失败，请稍后再试");
            }

            // 7. 刷新页面（重新加载项目列表）
            request.setAttribute("projectList", projectDAO.getProjectList());
            request.getRequestDispatcher("/WEB-INF/views/member/reservationForm.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
            // 重新加载项目列表并显示错误
            ProjectDAO projectDAO = new ProjectDAO();
            request.setAttribute("projectList", projectDAO.getProjectList());
            request.setAttribute("error", "预约处理出错：" + e.getMessage());
            request.getRequestDispatcher("/WEB-INF/views/member/reservationForm.jsp").forward(request, response);
        }
    }

    // 辅助方法：解析预约时间，处理格式转换
    private Timestamp parseReservationTime(String timeStr) {
        if (timeStr == null || timeStr.isEmpty()) {
            return null;
        }

        try {
            // 方法1：使用Java 8日期时间API（推荐）
            LocalDateTime dateTime = LocalDateTime.parse(timeStr);
            return Timestamp.valueOf(dateTime);

        } catch (DateTimeParseException e) {
            try {
                // 方法2：手动处理格式（兼容旧版本Java）
                String formattedTime = timeStr.replace("T", " ") + ":00";
                return Timestamp.valueOf(formattedTime);

            } catch (IllegalArgumentException ex) {
                // 格式仍然不匹配
                return null;
            }
        }
    }
}